<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="序号" prop="mark">
              <el-input v-model="queryParams.mark" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="购买类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择购买类型" clearable>
                <el-option v-for="dict in biz_pruchase_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="充值金额" prop="amount">
              <el-input v-model="queryParams.amount" placeholder="请输入充值金额" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="hash" prop="txHash">
              <el-input v-model="queryParams.txHash" placeholder="请输入hash" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="时间" prop="transferTime">
              <el-date-picker
                v-model="queryParams.transferTime"
                clearable
                type="daterange"
                value-format="YYYY-MM-DD"
                placeholder="请选择时间"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="转出地址" prop="fromAddress">
              <el-input v-model="queryParams.fromAddress" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="转入地址" prop="toAddress">
              <el-input v-model="queryParams.toAddress" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:userInvest:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:userInvest:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:userInvest:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:userInvest:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :offset="1.5" :span="1.5">
            <span style="color: red">总投资金额：{{ userInvestStatisticsVo.totalInvestAmount }}</span>
          </el-col>
          <el-col :offset="1.5" :span="1.5">
            <span style="color: red">总投资人数：{{ userInvestStatisticsVo.totalInvestUserNum }}</span>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userInvestList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="主键" align="center" prop="id" show-overflow-tooltip />
        <el-table-column label="用户id" align="center" prop="userId" />
        <el-table-column label="序号" align="center" prop="mark" />
        <el-table-column label="订单编号" align="center" prop="orderSn" width="200" />
        <el-table-column label="购买类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="biz_pruchase_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="充值数量" align="center" prop="purchaseAmount" width="150" />
        <el-table-column label="价值usdt" align="center" prop="amount" width="150" />
        <el-table-column label="hash" align="center" prop="txHash" width="200" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="error">错误数据</el-tag>
            <el-tag v-else-if="scope.row.status == 1" type="primary">待确认</el-tag>
            <el-tag v-else-if="scope.row.status == 2" type="success">确认到账</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="转出地址" align="center" prop="fromAddress" width="350" show-overflow-tooltip>
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center; cursor: pointer" @click="copy(scope.row.fromAddress)">
              {{ scope.row.fromAddress }}
              <el-icon style="margin-left: 5px"><CopyDocument /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="转入地址" align="center" prop="toAddress" width="350" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.toAddress }}
          </template>
        </el-table-column>
        <el-table-column label="链上详情" align="center" prop="notifyData" width="200" show-overflow-tooltip />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:userInvest:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:userInvest:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户投资记录对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="userInvestFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="hash" prop="txHash">
          <el-input v-model="form.txHash" placeholder="请输入hash" />
        </el-form-item>
        <el-form-item label="时间" prop="transferTime">
          <el-date-picker v-model="form.transferTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserInvest" lang="ts">
import { listUserInvest, queryUserInvestStatistics, getUserInvest, delUserInvest, addUserInvest, updateUserInvest } from '@/api/business/userInvest';
import { UserInvestVO, UserInvestQuery, UserInvestForm } from '@/api/business/userInvest/types';

import useClipboard from 'vue-clipboard3';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 数据初始化定义 */
const { toClipboard } = useClipboard();
const { biz_pruchase_type } = toRefs<any>(proxy?.useDict('biz_pruchase_type'));

const userInvestList = ref<UserInvestVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userInvestFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const userInvestStatisticsVo = ref({
  'totalInvestAmount': 0,
  'totalInvestUserNum': 0
});

const initFormData: UserInvestForm = {
  id: undefined,
  userId: undefined,
  orderSn: undefined,
  amount: undefined,
  txHash: undefined,
  status: undefined,
  transferTime: undefined,
  fromAddress: undefined,
  toAddress: undefined,
  notifyData: undefined,
  remark: undefined
};
const data = reactive<PageData<UserInvestForm, UserInvestQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    mark: undefined,
    type: undefined,
    orderSn: undefined,
    amount: undefined,
    txHash: undefined,
    status: undefined,
    transferTime: undefined,
    fromAddress: undefined,
    toAddress: undefined,
    notifyData: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
    orderSn: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '充值金额不能为空', trigger: 'blur' }],
    txHash: [{ required: true, message: 'hash不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    transferTime: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
    fromAddress: [{ required: true, message: '不能为空', trigger: 'blur' }],
    toAddress: [{ required: true, message: '不能为空', trigger: 'blur' }],
    notifyData: [{ required: true, message: '不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户投资记录列表 */
const getList = async () => {
  loading.value = true;

  let startTime = null,
    endTime = null;
  if (queryParams.value.transferTime) {
    startTime = queryParams.value.transferTime[0] + ' 00:00:00';
    endTime = queryParams.value.transferTime[1] + ' 23:59:59';
    // queryParams.value.transferTime = null
  }
  let queryParamsClone = JSON.parse(JSON.stringify(queryParams.value));
  delete queryParamsClone['transferTime'];
  const res = await listUserInvest({
    ...queryParamsClone,
    startTime,
    endTime
  });
  const userInvestStatistics = await queryUserInvestStatistics({
    ...queryParamsClone,
    startTime,
    endTime
  });
  userInvestStatisticsVo.value = userInvestStatistics.data;
  userInvestList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userInvestFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserInvestVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加用户投资记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserInvestVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUserInvest(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改用户投资记录';
};

/** 提交按钮 */
const submitForm = () => {
  userInvestFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserInvest(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserInvest(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserInvestVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户投资记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUserInvest(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/userInvest/export',
    {
      ...queryParams.value
    },
    `userInvest_${new Date().getTime()}.xlsx`
  );
};

const copy = async (address: any) => {
  // navigator.clipboard.writeText(address);
  // 如果clipboard API失败，可以回退到使用document.execCommand()方法
  try {
    await navigator.clipboard.writeText(address);
    ElMessage.success('复制成功');
  } catch (err) {
    console.error('复制失败', err);
    // 如果clipboard API失败，可以回退到使用document.execCommand()方法
    copyContent2(address);
  }
};

// 复制文本内容方法二
const copyContent2 = (text: any) => {
  // 复制结果
  let copyResult = true;
  // 创建一个input元素
  let inputDom = document.createElement('textarea');
  // 设置为只读 防止移动端手机上弹出软键盘
  inputDom.setAttribute('readonly', 'readonly');
  // 给input元素赋值
  inputDom.value = text;
  // 将创建的input添加到body
  document.body.appendChild(inputDom);
  // 选中input元素的内容
  inputDom.select();
  // 执行浏览器复制命令
  // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签中的内容）
  // Input要在正常的编辑状态下原生复制方法才会生效
  const result = document.execCommand('copy');
  // 判断是否复制成功
  if (result) {
    ElMessage.success('复制成功');
  } else {
    console.log('复制失败');
    copyResult = false;
  }
  // 复制操作后再将构造的标签 移除
  document.body.removeChild(inputDom);
  // 返回复制操作的最终结果
  return copyResult;
};

onMounted(() => {
  getList();
});
</script>
